<?php
/**
 * User: @lixu
 * Date: 2019-08-12
 * Time: 14:36
 */

use Doraemon\service\Login;
use Doraemon\tools\HhzClient as tHhzClient;
use Doraemon\tools\Log as tLog;
use EasyWeChat\Factory;
use Infinity\cache\designerVote\OutUser as cOutUser;
use Infinity\service\designerVote\HomePage as sHomePage;
/**
 * @deprecated
 */
class HomePageAction extends ActionPlugin
{

    const USER_LEVEL = self::LEVEL_NOTHING;

    public function main()
    {
        $uid = $this->checkType();

        $voteNumber = sHomePage::getUserVoteNumber($uid); // 获取用户票数

        $voteHistoryList = sHomePage::getHistory($uid); // 获取用户投票记录信息

        $leaderBoardList = sHomePage::getLeaderBoard(); // 获取排行榜单信息

        $list['list'] = [
            'vote_number' => $voteNumber,
            'vote_history' => $voteHistoryList,
            'popularity_list' => $leaderBoardList['popularityList'],
            'designer_recommend_list' => $leaderBoardList['designerRecommendList'],
            'owner_list' => $leaderBoardList['ownerList']
        ];

        $this->setSuccess($list);
    }

    public function checkType()
    {
        if($this->browserType == tHhzClient::BROWSERTYPE_WECHAT) {
            $openId = $this->getRequest()->getPost('openid');
            $accessToken = $this->getRequest()->getPost('access_token');
            tLog::debug('首页接收openid和access_token', [$openId, $accessToken]);
            // 走微信的验证逻辑

            if(!$openId) {
                tLog::debug('openid为空不存在', [$openId]);
                throw new \Exception('访问失败，请重试');
            }


            if(!$accessToken) {
                tLog::debug('accessToken不存在', [$accessToken]);
                throw new \Exception('访问失败，请重试');
            }

            $result = cOutUser::getItem($openId);
            if(!$result) {
                Login::checkWeixinAuth($accessToken, $openId);

                $config = [
                    'app_id' => 'wx8cfd0f432ddd6c4a',
                    'secret' => 'f2ade2c8485f7222e95acde04d1a8448'
                ];
                $app = Factory::officialAccount($config);
                $user = $app->user->get($openId);
                if($user['errcode'] != 0) {
                    tLog::debug('请求微信验证失败', [$user]);
                    throw new \Exception('账号异常');
                }
                cOutUser::setItem($openId, $openId);
            }
            $uid = $openId;
        } else if (tHhzClient::$client_type == tHhzClient::APPTYPE_IOS || tHhzClient::$client_type == tHhzClient::APPTYPE_ANDROID) {
            $uid = $this->uid;
        } else {
            throw new \Exception('请在好好住APP或者微信内打开页面!');
        }

        return $uid;
    }
}